// miniprogram/pages/home/home.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    selected: [],
    avatarUrl: '../../images/user-unlogin.png',
    nickName: '',
    logged: false,
    userInfo: {},
    days: 0,
    money: 0,
    todayDate: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              that.setData({
                avatarUrl: res.userInfo.avatarUrl,
                nickName: res.userInfo.nickName,
                userInfo: res.userInfo,
                logged: true,
              })
              wx.setStorageSync('nickName', res.userInfo.nickName)
            }
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.getRecords()
  },

  /**
   * 获取记录
   */
  getRecords: function(e) {
    var that = this;
    let selected = []
    let days = 0
    let money = 0
    console.log('openid:', wx.getStorageSync('openid'))
    if (wx.getStorageSync('openid')) {
      wx.cloud.callFunction({
        name: 'getRecords',
        data: {
          userid: wx.getStorageSync('openid')
        },
        success: res => {
          console.log('[云函数] [getRecords] 调用成功: ', res.result.data)
          for (var i = 0; i < res.result.data.length; i++) {
            var item = {
              date: res.result.data[i].time
            }
            selected.push(item)
            money = money + parseInt(res.result.data[i].money)
          }
          that.setData({
            selected: selected,
            days: res.result.data.length,
            money: money
          })
        },
        fail: err => {
          console.error('[云函数] [getRecords] 调用失败', err)
        }
      })
    }
  },

  /**
   * 获取选择日期
   */
  bindgetdate(e) {
    let time = e.detail.year + '-' + e.detail.month + '-' + e.detail.date;
    console.log('选择日期:', time)
    this.setData({
      todayDate: time
    })
  },

  /**
   * 添加记录
   */
  clickAddBtn: function(e) {
    console.log(e)
    var that = this;
    if (!that.data.logged && e.detail.userInfo) {
      wx.setStorageSync('nickName', e.detail.userInfo.nickName)
      that.setData({
        logged: true,
        avatarUrl: e.detail.userInfo.avatarUrl,
        nickName: e.detail.userInfo.nickName,
        userInfo: e.detail.userInfo
      })
      if (!wx.getStorageSync('openid')) {
        wx.cloud.callFunction({
          name: 'login',
          data: {},
          success: res => {
            console.log('[云函数] [login] user openid: ', res.result.openid)
            wx.setStorageSync('openid', res.result.openid)
            that.addUser(res.result.openid, e.detail.userInfo)
            that.getRecords()
          },
          fail: err => {
            console.error('[云函数] [login] 调用失败', err)
          }
        })
      }
    } else {
      that.addUser(wx.getStorageSync('openid'), e.detail.userInfo)
      if (e.detail.errMsg != 'getUserInfo:fail auth deny') {
        wx.navigateTo({
          url: '../addRecord/addRecord?todayDate=' + that.data.todayDate,
        })
      }
    }
  },

  /**
   * 添加用户
   * openid（用户id），头像，昵称，性别，省份，城市
   */
  addUser: function(openid, userInfo) {
    const db = wx.cloud.database()
    db.collection('users').where({
      userid: openid
    }).get({
      success(res) {
        console.log(res)
        if (res.data.length == 0) {
          console.log('用户查询成功可添加')
          db.collection('users').add({
            data: {
              userid: openid,
              avatarUrl: userInfo.avatarUrl,
              nickName: userInfo.nickName,
              gender: userInfo.gender,
              province: userInfo.province,
              city:userInfo.city,
              days:0
            },
            success(res) {
              console.log('用户添加成功:',res)
              // let _id = res._id
              // db.collection('records').where({
              //   userid:openid
              // }).count({
              //   success(res) {
              //     console.log(res.total)
              //     let total = res.total
              //     db.collection('users').doc(_id).update({
              //       data: {
              //         days: total
              //       },
              //       success: console.log,
              //       fail: console.error
              //     })
              //   }
              // })
            }
          })
        } else {
          console.log('此用户已存在')
        }
      }
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})